package com.rem.chat.controller;

import com.rem.chat.aop.annotation.GlobalInterceptor;
import com.rem.chat.common.config.AppConfig;
import com.rem.chat.common.constants.Constants;
import com.rem.chat.common.utils.JacksonUtil;
import com.rem.chat.common.utils.RedisComponent;
import com.rem.chat.common.utils.RedisUtil;
import com.rem.chat.pojo.request.UserStatusModifyRequest;
import com.rem.chat.pojo.request.PageRequest;
import com.rem.chat.pojo.request.SysSettingSaveRequest;
import com.rem.chat.pojo.response.CommonResult;
import com.rem.chat.pojo.response.LoadAllGroupResponse;
import com.rem.chat.pojo.response.LoadAllUserResponse;
import com.rem.chat.pojo.response.SystemSettingResponse;
import com.rem.chat.service.AdminService;
import com.rem.chat.service.dto.UserLoginDTO;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: Themberfue
 * @date: 2025/6/9 17:04
 * @description:
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    @Resource(name = "adminServiceImpl")
    AdminService adminService;

    @Resource
    RedisComponent redisComponent;

    @Resource
    RedisUtil redisUtil;

    @Resource
    AppConfig appConfig;

    @GetMapping("/loadAllUser")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<LoadAllUserResponse> loadAllUser(@RequestBody @Nullable @Validated PageRequest param) {
        log.info("loadAllUser PageRequest:{}", JacksonUtil.writeValueAsString(param));

        return CommonResult.success(
                adminService.loadAllUser(param));
    }

    @PutMapping("/modifyUserStatus")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<Boolean> modifyUserStatus(@RequestBody @Validated UserStatusModifyRequest request) {
        log.info("modifyUserStatus UserStatusModifyRequest:{}", JacksonUtil.writeValueAsString(request));

        return CommonResult.success(
                adminService.modifyUserStatus(request));
    }

    @PutMapping("/forceOffLine")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<Boolean> forceOffLine(@NotEmpty String userId) {
        log.info("forceOffLine userId:{}", userId);

        return CommonResult.success(
                adminService.forceOffLine(userId));
    }

    @GetMapping("/loadAllGroup")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<LoadAllGroupResponse> loadAllGroup(@RequestBody @Nullable @Validated PageRequest param) {
        log.info("loadAllGroup PageRequest:{}", JacksonUtil.writeValueAsString(param));

        return CommonResult.success(
                adminService.loadAllGroup(param));
    }

    @DeleteMapping("/dissolutionGroup")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<Boolean> dissolutionGroup(@NotBlank String groupId, HttpServletRequest request) {
        log.info("dissolutionGroup groupId:{}", groupId);

        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        return CommonResult.success(
                adminService.dissolutionGroup(groupId, user.getUserId()));
    }


    @GetMapping("/getSysSetting")
    @GlobalInterceptor
    public CommonResult<SystemSettingResponse> getSysSetting() {
        return CommonResult.success(
                redisComponent.getSystemSetting());
    }

    @PostMapping("/saveSysSetting")
    @GlobalInterceptor(checkAdmin = true)
    public CommonResult<SystemSettingResponse> saveSysSetting(@RequestPart @Validated SysSettingSaveRequest param,
                                                              MultipartFile robotFile,
                                                              MultipartFile robotCover,
                                                              HttpServletRequest request) throws IOException {
        log.info("saveSysSetting SysSettingSaveRequest:{}", JacksonUtil.writeValueAsString(param));

        // Step 1. 保存头像到服务器
        saveRobotAvatarAndCover(robotFile, robotCover);

        // Step 2. 将系统设置存至缓存
        return CommonResult.success(
                redisComponent.saveSysSetting(param));
    }

    /**
     * 保存机器人头像和封面图片到服务器
     * @param robotFile 机器人头像
     * @param robotCover 机器人头像缩略图
     */
    private void saveRobotAvatarAndCover(MultipartFile robotFile, MultipartFile robotCover) throws IOException {
        if (null != robotFile) {
            File targetFileFolder = new File(appConfig.getProjectFolder() +
                    Constants.FILE_FOLDER_AVATAR);
            if (!targetFileFolder.exists()) {
                targetFileFolder.mkdirs();
            }
            String robotFilePath = targetFileFolder.getPath() + "/" + Constants.ROBOT_UID + Constants.IMAGE_SUFFIX;
            String robotCoverPath = targetFileFolder.getPath() + "/" + Constants.ROBOT_UID + Constants.COVER_IMAGE_SUFFIX;
            robotFile.transferTo(new File(robotFilePath));
            robotCover.transferTo(new File(robotCoverPath));
        }
    }

    private UserLoginDTO getUserLoginDTO(HttpServletRequest request) {
        String token = request.getHeader("token");
        String user = redisUtil.get(Constants.REDIS_KEY_WS_TOKEN + token);
        log.info("user: {}", user);
        return JacksonUtil.readValue(user, UserLoginDTO.class);
    }
}
